package com.tiger.cloud.controller.crm;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiger.cloud.auth0.jwt.Token;
import com.tiger.cloud.auth0.jwt.TokenGenerator;
import com.tiger.cloud.auth0.jwt.exceptions.JWTCreationException;
import com.tiger.cloud.auth0.jwt.interfaces.Claim;
import com.tiger.cloud.common.jpush.JpushInterface;
import com.tiger.cloud.common.mapper.JsonMapper;
import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.common.token.PasswordHashUtil;
import com.tiger.cloud.common.view.SpringUtils;
import com.tiger.cloud.enums.AppSmsType;
import com.tiger.cloud.enums.DeleteEnum;
import com.tiger.cloud.enums.RecommandListAcceptStatus;
import com.tiger.cloud.enums.RecommandListStatus;
import com.tiger.cloud.enums.UserStatusEnum;
import com.tiger.cloud.enums.UserWeChatEnum;
import com.tiger.cloud.filter.CurrentUserId;
import com.tiger.cloud.filter.CurrentUserLoginId;
import com.tiger.cloud.filter.CurrentUserWeixin;
import com.tiger.cloud.filter.IgnoreAuth;
import com.tiger.cloud.form.AppSmsMessages;
import com.tiger.cloud.form.CompanyForm;
import com.tiger.cloud.form.ReferTokenForm;
import com.tiger.cloud.form.SysDictSmall;
import com.tiger.cloud.form.UserLoginForm;
import com.tiger.cloud.model.crm.AppSms;
import com.tiger.cloud.model.crm.RecommandList;
import com.tiger.cloud.model.crm.User;
import com.tiger.cloud.model.crm.UserCompanyInfo;
import com.tiger.cloud.model.crm.UserInfo;
import com.tiger.cloud.model.ext.UserAndCompanyInfo;
import com.tiger.cloud.model.ext.UserInfoAndCompany;
import com.tiger.cloud.model.ext.UserInfos;
import com.tiger.cloud.model.rejection.Rejection;
import com.tiger.cloud.model.share.ShareQuery;
import com.tiger.cloud.model.system.DataObject;
import com.tiger.cloud.model.system.SysScheduleJob;
import com.tiger.cloud.service.crm.IAppSmsService;
import com.tiger.cloud.service.crm.IRecommandListService;
import com.tiger.cloud.service.crm.IUserCompanyInfoService;
import com.tiger.cloud.service.crm.IUserInfoService;
import com.tiger.cloud.service.crm.IUserService;
import com.tiger.cloud.service.rejection.IRejectionService;
import com.tiger.cloud.service.share.IShareService;
import com.tiger.cloud.service.system.CommonDict;
import com.tiger.cloud.service.system.ISysScheduleJobService;
import com.tiger.cloud.util.CookieManager;
import com.tiger.cloud.util.DateTimeUtil;
import com.tiger.cloud.util.ErrorCode;
import com.tiger.cloud.util.MagicConstants;
import com.tiger.cloud.util.Page;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;
import com.tiger.cloud.util.StringUtil;
import com.tiger.cloud.util.weChat.AccessToken;

import cn.jpush.api.push.PushResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 用户管理
 */
@Controller
@RequestMapping(value = "user")
@Api(value = "用户管理",tags = "用户")
public class UserController extends BaseController {

	@Autowired
	private IUserService userService;
	@Autowired
	private IAppSmsService appSmsService;
	@Autowired
	private IUserInfoService userInfoService;
	@Autowired
	private IUserCompanyInfoService userCompanyInfoService;
	@Autowired
	private IRecommandListService recommandListService ;
	@Autowired
	private JpushInterface jpushInterface;
	@Autowired
	private ISysScheduleJobService sysScheduleJobService; 
	@Autowired
	private IRejectionService rejectionService;
	@Autowired
    private IShareService shareService;
	
	private static final Logger logger = Logger.getLogger(UserController.class);
	
	/**
	 * 测试推送
	 */
	@IgnoreAuth
	@RequestMapping(value = "test01", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "测试推送",notes = "测试推送")
	public Response test01(){
		List<User> users=SpringUtils.getBean(IRecommandListService.class).notAcceptCount();
		for (User user : users) {
			if(StringUtils.isNotEmpty(user.getJpushCode())){
				String msg="有"+user.getCount()+"个同行对您感兴趣，已添加了您，请予已接受，以便你们后续合作交流";
				Map<String, Object> data=new HashMap<String, Object>();
				Map<String, Object> params=new HashMap<String, Object>();
				params.put("id", null);
				params.put("content",msg);
				data.put("type", "1");
				data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
				SpringUtils.getBean(JpushInterface.class).sendPushMessage(user.getJpushCode(),"notification", data);
			}
		}
		return ResponseUtil.ok();
	}
	
	/**
	 * 测试推送
	 */
	@IgnoreAuth
	@RequestMapping(value = "test02", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "测试推送2",notes = "测试推送2")
	public Response test02(){
		List<User> users=SpringUtils.getBean(IRecommandListService.class).notAddCount();
		long userCount=SpringUtils.getBean(IUserService.class).countByEntity(new User());
		for (User user : users) {
			String msg="您还有"+(userCount-user.getCount())+"个同行未添加，请及时添加为您的人脉，以便需要时能够立即沟通联系";
			Map<String, Object> data=new HashMap<String, Object>();
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("id", null);
			params.put("content",msg);
			data.put("type", "1");
			data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
			SpringUtils.getBean(JpushInterface.class).sendPushMessage(user.getJpushCode(),"notification", data);
		}
		return ResponseUtil.ok();
	}
	
	
	/**
	 * 测试推送
	 */
	@IgnoreAuth
	@RequestMapping(value = "test03", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "测试推送3",notes = "测试推送2")
	public Response test03(){
		Rejection findRejection=new Rejection();
		findRejection.setPageSize(Integer.MAX_VALUE);
		List<Rejection> rejections=SpringUtils.getBean(IRejectionService.class).findDayNotEnd(findRejection);
		for (Rejection rejection : rejections) {
			String typeText="";
			if(rejection.getLoanType().equals("0")){
				typeText="车辆抵押";
			}else if(rejection.getLoanType().equals("1")){
				typeText="无抵押";
			}else if(rejection.getLoanType().equals("2")){
				typeText="零用贷";
			}else if(rejection.getLoanType().equals("3")){
				typeText="垫资";
			}else if(rejection.getLoanType().equals("4")){
				typeText="不动产抵押";
			}else if(rejection.getLoanType().equals("5")){
				typeText="其他抵押";
			}else if(rejection.getLoanType().equals("6")){
				typeText="银行中介";
			}else if(rejection.getLoanType().equals("7")){
				typeText="资方";
			}else if(rejection.getLoanType().equals("8")){
				typeText="金融律师";
			}else if(rejection.getLoanType().equals("9")){
				typeText="征信查询";
			}else if(rejection.getLoanType().equals("10")){
				typeText="催收";
			}else if(rejection.getLoanType().equals("11")){
				typeText="资产处理";
			}else if(rejection.getLoanType().equals("12")){
				typeText="其他金服";
			}else if(rejection.getLoanType().equals("13")){
				typeText="房产经纪人";
			}else if(rejection.getLoanType().equals("14")){
				typeText="车辆经纪人";
			}else if(rejection.getLoanType().equals("15")){
				typeText="保险经纪人";
			}
			String msString="您发布的甩单信息\""+typeText+","+rejection.getAmount()+"万,"+rejection.getLoanTerm()+"个月\",目前仍未完成，建议调整内容后重新发布，预祝您顺利找到合适的接单人!";
			Map<String, Object> data=new HashMap<String, Object>();
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("id", null);
			params.put("content",msString);
			data.put("type", "1");
			data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
			SpringUtils.getBean(JpushInterface.class).sendPushMessage(rejection.getJpushCode(),"notification", data);
		}
		return ResponseUtil.ok();
	}
	
	/**
	 * 根据二维码获取用户信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "getByQRCode", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "根据二维码获取用户信息",notes = "根据二维码获取用户信息")
	public Response getByQRCode(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@ApiParam(name="loginId",value="用户LoginId",hidden=true) @CurrentUserLoginId String mobile,
			@ApiParam(name="weixin",value="用户Weixin",hidden=true) @CurrentUserWeixin String weixin,
			@RequestBody UserLoginForm userLoginForm){
		if(StringUtils.isEmpty(userLoginForm.getQrCode())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"qrCode必传");
		}
		User queryUser=new User();
		queryUser.setIsDelete(DeleteEnum.NOMAIL);
		queryUser.setQrCode(userLoginForm.getQrCode());
		User user=userService.findOne(queryUser);
		if(user==null){
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		UserInfo findUserInfo=new UserInfo();
		findUserInfo.setUserId(user.getId());
		UserInfo userInfo = userInfoService.findOne(findUserInfo);
		if (userInfo == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		if(userInfo.getLoginId().equals(mobile)||((!StringUtils.isEmpty(userInfo.getWeiXin()))&&userInfo.getWeiXin().equals(weixin))){
			return ResponseUtil.error(ErrorCode.UN_ADD_USER,"无法添加当前用户为好友!");
		}
		RecommandList findRecommandList=new RecommandList();
		findRecommandList.setIsDelete(DeleteEnum.NOMAIL);
		findRecommandList.setRecommandId(user.getId());
		findRecommandList.setUserId(userId);
		RecommandList recommandList=recommandListService.getRecommand(findRecommandList);
		if(recommandList!=null && (recommandList.getUserId().longValue()==userId.longValue() && recommandList.getIsDelete()==DeleteEnum.NOMAIL)&&recommandList.getStatus()==RecommandListStatus.CREATED){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",user);
		}else if(recommandList!=null && (recommandList.getRecommandId().longValue()==userId.longValue() && recommandList.getAcceptIsDelete()==DeleteEnum.NOMAIL&&recommandList.getAcceptStatus()==RecommandListAcceptStatus.ACCEPTED)){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",user);
		}
		return ResponseUtil.ok(user);
	}
	
	/**
	 * 根据用户user_id获取用户信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "getById", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "根据手机号获取用户信息",notes = "根据手机号获取用户信息")
	public Response getById(Long userId){
		if(userId==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"userId必传");
		}
		UserInfo userInfo = userInfoService.get(userId);
		return ResponseUtil.ok(userInfo);
	}
	
	
	/**
	 * 根据手机号获取用户信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "getByMobile", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "根据手机号获取用户信息",notes = "根据手机号获取用户信息")
	public Response getByMobile(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@ApiParam(name="loginId",value="用户LoginId",hidden=true) @CurrentUserLoginId String mobile,
			@ApiParam(name="weixin",value="用户Weixin",hidden=true) @CurrentUserWeixin String weixin,
			@RequestBody UserLoginForm userLoginForm){
		if(StringUtils.isEmpty(userLoginForm.getLoginId())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传");
		}
		UserInfo userInfo = userInfoService.findUser(userLoginForm.getLoginId());
		if (userInfo == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		if(userInfo.getLoginId().equals(mobile)||((!StringUtils.isEmpty(userInfo.getWeiXin()))&&userInfo.getWeiXin().equals(weixin))){
			return ResponseUtil.error(ErrorCode.UN_ADD_USER,"无法添加当前用户为好友!");
		}
		User queryUser=new User();
		queryUser.setIsDelete(DeleteEnum.NOMAIL);
		queryUser.setLoginId(userInfo.getLoginId());
		User userObj=userService.findOne(queryUser);
		if(userObj==null){
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"不存在该用户!");
		}
		RecommandList findRecommandList=new RecommandList();
		findRecommandList.setRecommandId(userObj.getId());
		findRecommandList.setUserId(userId);
		findRecommandList.setIsDelete(DeleteEnum.NOMAIL);
		RecommandList recommandList=recommandListService.getRecommand(findRecommandList);
		if(recommandList!=null && (recommandList.getUserId().longValue()==userId.longValue() && recommandList.getIsDelete()==DeleteEnum.NOMAIL)&&recommandList.getStatus()==RecommandListStatus.CREATED){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",userInfo);
		}else if(recommandList!=null && (recommandList.getRecommandId().longValue()==userId.longValue() && recommandList.getAcceptIsDelete()==DeleteEnum.NOMAIL&&recommandList.getAcceptStatus()==RecommandListAcceptStatus.ACCEPTED)){
			return ResponseUtil.errorData(ErrorCode.OBJECT_EXITS,"对象已经存在",userInfo);
		}
		return ResponseUtil.ok(userInfo);
	}

	@IgnoreAuth
	@RequestMapping(value = "get", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取默认用户信息",notes = "获取默认用户信息")
	public Response get(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId){
		UserAndCompanyInfo userAndCompanyInfo = userInfoService.getUserAndCompanyInfo(userId) ;
		return ResponseUtil.ok(userAndCompanyInfo);
	}
	
	@RequestMapping(value = "getUserAndCompanyInfo", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@IgnoreAuth
	@ApiOperation(value = "获取默认用户信息",notes = "获取默认用户信息")
	public Response getUserAndCompanyInfo(@RequestBody Long userId){
		if(userId==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"userId必传!");
		}
		UserAndCompanyInfo userAndCompanyInfo= userInfoService.getUserAndCompanyInfo(userId) ;
		return ResponseUtil.ok(userAndCompanyInfo);
	}

	@RequestMapping(value = "findUserAndCompanyInfo", method = RequestMethod.POST)
	@IgnoreAuth
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取单条用户信息",notes = "获取单条用户信息")
	public Response findUserAndCompanyInfo(@RequestBody User user){
		if(null == user.getId()){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"userId必传!");
		}
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		Map<String, List<SysDictSmall>> companyValues = CommonDict.getFileds("user_company_info");
		List<UserInfoAndCompany> userAndCompanyInfo= userService.findUserAndCompanyInfo(user.getId()) ;
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("userAndCompanyInfo", userAndCompanyInfo);
		maps.put("defaultInfo", values);
		maps.put("defaultCompany", companyValues);

		return ResponseUtil.ok(maps);
	}
	
	/**
	 * 获取列表默认值
	 */
	@IgnoreAuth
	@RequestMapping(value = "getUserInfo", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取列表默认值",notes = "获取列表默认值")
	public Response getDefaultFileds(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,
			@ApiParam(name="id",value="用户手机号",hidden=true) @CurrentUserLoginId String mobile){
		UserInfo userInfo=new UserInfo();
		userInfo.setIsDelete(DeleteEnum.NOMAIL);
		userInfo.setUserId(userId);
		UserInfo findUserInfo=userInfoService.findOne(userInfo);
		findUserInfo.setLoginId(mobile);
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		Map<String, Object> maps=new HashMap<String, Object>();
		maps.put("userInfo", findUserInfo);
		maps.put("defaults", values);
		return ResponseUtil.ok(maps);
	}
	
	/**
	 * 获取列表默认值
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "getDefaultFileds", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "获取列表默认值",notes = "获取列表默认值")
	public Response getDefaultFileds(){
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		return ResponseUtil.ok(values);
	}
	
	/**
	 * 忘记密码
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "forgotPassword", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "忘记密码",notes = "忘记密码")
	public Response forgotPassword(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId, @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传");
		}
		//发送验证码
		AppSms appVerifCode=new AppSms();
		appVerifCode.setPhone(userLoginForm.getLoginId());
		appVerifCode.setOrderBy("create_time desc");
		appVerifCode.setCode(userLoginForm.getVerifCode());
		AppSms findAppVerifCode=appSmsService.findOne(appVerifCode);
		if(findAppVerifCode==null){
			return ResponseUtil.error(ErrorCode.INVALID_AUTHENTICATION_CODE,"无效的验证码");
		}
		if(DateTimeUtil.getMillisecondsOfTwoDate(findAppVerifCode.getActiveTime(), DateTimeUtil.getSystemDate())<0){
			return ResponseUtil.error(ErrorCode.VERIFICATION_CODE_EXPIRED,"验证码已过期");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"password必传");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户已近存在");
		}
		if (user.getStatus() == UserStatusEnum.AUDIT) {
			return ResponseUtil.error("用户处于审核中,暂时无法操作");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			return ResponseUtil.error("用户处于冻结中,暂时无法操作");
		}
		//更新密码
		User updateUser=new User();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginForm.getPassword()));
		userService.update(updateUser);
		return ResponseUtil.ok();
	}
	
	/**
	 * 修改密码
	 */
	@IgnoreAuth
	@RequestMapping(value = "updatePassword", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "修改密码",notes = "修改密码")
	public Response updatePassword(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId, @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"password必传");
		}
		if (StringUtils.isEmpty(userLoginForm.getOldPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"oldPassword必传");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		if (user.getStatus() == UserStatusEnum.AUDIT) {
			return ResponseUtil.error("用户处于审核中,暂时无法操作");
		}
		if (user.getStatus() == UserStatusEnum.DISABLE) {
			return ResponseUtil.error("用户处于冻结中,暂时无法操作");
		}
		if (!PasswordHashUtil.validatePassword(userLoginForm.getOldPassword(), user.getPassword())) {
            return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID,"密码错误");
        }
		//更新密码
		User updateUser=new User();
		updateUser.setId(user.getId());
		updateUser.setPassword(PasswordHashUtil.createHash(userLoginForm.getPassword()));
		if(userService.update(updateUser)>0){
			return ResponseUtil.ok();
		}
		return ResponseUtil.error(ErrorCode.INTERNAL_ERROR,"密码错误,请重新登录");
	}
	
	/**
	 * 处理用户注册
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "处理用户注册",notes = "处理用户注册")
	public Response register(  @RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数loginId必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数password必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getBrowser())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数browser必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getMacUid())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数macUid必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getIp())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"参数ip必传!");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User findUserObj =userService.findOne(findUser);
		if(findUserObj!=null){
			return ResponseUtil.error(ErrorCode.OBJECT_EXITS,"用户已经存在!");
		}
//		AppSms appVerifCode=new AppSms();
//		appVerifCode.setPhone(userLoginForm.getLoginId());
//		appVerifCode.setOrderBy("create_time desc");
//		appVerifCode.setCode(userLoginForm.getVerifCode());
//		AppSms findAppVerifCode=appSmsService.findOne(appVerifCode);
//		if(findAppVerifCode==null){
//			return ResponseUtil.error(ErrorCode.INVALID_AUTHENTICATION_CODE,"无效的验证码");
//		}
//		if(DateTimeUtil.getMillisecondsOfTwoDate(findAppVerifCode.getActiveTime(), DateTimeUtil.getSystemDate())<0){
//			return ResponseUtil.error(ErrorCode.VERIFICATION_CODE_EXPIRED,"验证码已过期");
//		}

		//注册完成,此用户处于待审核阶段
		User user= userService.register(userLoginForm);
		if (user==null) {
			return ResponseUtil.error(ErrorCode.USER_PASSWORD_INVALID,"密码无效!");
		}
		Map<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("userId",user.getId());
		return ResponseUtil.ok(dataMap);
	}
	

	/**
	 * 处理用户注册--->完善用户信息
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "authCompany1", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "完善用户注册信息",notes = "处理用户注册--->完善用户信息")
	public Response authCompany1(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody String jpushCode) {
		String msString= "恭喜您成为安石派的会员，同行大厅有"+100+"个同行等待你去添加，安石派会助您迅速扩展人 脉、提升业绩！";
		
		List<String> clientList=new ArrayList<String>();
		clientList.add(jpushCode);
		try {
			
			Map<String, Object> data=new HashMap<String, Object>();
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("id", null);
			params.put("content",msString);
			data.put("type", "1");
			data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
			PushResult pushResult=jpushInterface.sendAllClientsPushMessage(clientList,"notification", data);
			System.out.println(JsonMapper.nonDefaultMapper().toJson(pushResult));

			java.util.Date  date=new java.util.Date();
			DataObject dataObject=new DataObject();
			dataObject.setJpushCode(clientList);
			dataObject.setMsg(msString);
			
			date=DateTimeUtil.addMinutes(date, 1);
			String cron=date.getSeconds()+ " "+DateTimeUtil.getMinutesOfHour(date)+" "+DateTimeUtil.getHoursOfDay(date)+" "+DateTimeUtil.getDayOfMonth(date)+" "+DateTimeUtil.getMonthOfYear(date)+" ? "+DateTimeUtil.getYearOfDate(date);
			SysScheduleJob scheduleJob2= new SysScheduleJob();
			scheduleJob2.setCronExpression(cron);
			scheduleJob2.setBeanClass("com.tiger.cloud.service.system.TaskExcutor");
			scheduleJob2.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
			scheduleJob2.setJobName("TaskExcutor.pushMsg.02."+100);
			scheduleJob2.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
			scheduleJob2.setMethodName("pushMsg");
			sysScheduleJobService.addJob(scheduleJob2);
			
			date=DateTimeUtil.addMinutes(date, 1);
			cron=date.getSeconds()+ " "+DateTimeUtil.getMinutesOfHour(date)+" "+DateTimeUtil.getHoursOfDay(date)+" "+DateTimeUtil.getDayOfMonth(date)+" "+DateTimeUtil.getMonthOfYear(date)+" ? "+DateTimeUtil.getYearOfDate(date);
			SysScheduleJob scheduleJob3= new SysScheduleJob();
			scheduleJob3.setCronExpression(cron);
			scheduleJob3.setBeanClass("com.tiger.cloud.service.system.TaskExcutor");
			scheduleJob3.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
			scheduleJob3.setJobName("TaskExcutor.pushMsg.03."+100);
			scheduleJob3.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
			scheduleJob3.setMethodName("pushMsg");
			sysScheduleJobService.addJob(scheduleJob3);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ResponseUtil.ok();
	}
	
	
	/**
	 * 处理用户注册--->完善用户信息
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "authCompany", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "完善用户注册信息",notes = "处理用户注册--->完善用户信息")
	public Response authCompany(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody CompanyForm companyForm) {
//		if(StringUtils.isEmpty(companyForm.getCompanyName())){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"companyName必传");
//		}
		if(userId==null&&companyForm.getUserId()==null){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"userId必传,注意这里注册时完善用户信息要填入userId,但是在登录后完善企业信息,则不传该值");
		}
		if(companyForm.getUserId()==null){
			companyForm.setUserId(userId);
		}
		UserCompanyInfo userCompanyInfo=userCompanyInfoService.register(companyForm);
		if (userCompanyInfo==null) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"注册企业信息无效,请重新选择!");
		}
		return ResponseUtil.ok();
	}
	
	
	/**
	 * 刷新用户Token
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "referToken", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "刷新用户Token",notes = "刷新用户Token")
	public Response referToken(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody ReferTokenForm referTokenForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		System.out.println("tokentokentokentokentokentokentokentoken:"+referTokenForm.getToken());
		if (StringUtils.isEmpty(referTokenForm.getToken())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"token必传");
		}
		Map<String, Claim> datas = TokenGenerator.getClaims(referTokenForm.getToken());
		Long userId_ = datas.get(MagicConstants.SESSION_USER_ID).asLong();
		String loginId = datas.get(MagicConstants.SESSION_USER_MOBILE).asString();

//		if(userId_!=userId){
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"只能刷新当前用户token!");
//		}
		User user = new User();
		user.setLoginId(loginId);
		user = userService.findOne(user);
		UserInfo userInfo = new UserInfo();
		System.out.println("user.getId()user.getId()user.getId()user.getId():"+user.getId());
		userInfo.setUserId(user.getId());
		userInfo = userInfoService.findOne(userInfo);
		System.out.println("userInfouserInfouserInfouserInfouserInfouserInfo:"+userInfo);
		Map<String, Object> claims = new HashMap<String, Object>();
		claims.put(MagicConstants.SESSION_USER_ID,userId_);
		claims.put(MagicConstants.SESSION_USER_MOBILE,loginId);
		claims.put(MagicConstants.SESSION_USER_JPUSH_CODE,user.getJpushCode());
		if ( null != userInfo ) {
			claims.put(MagicConstants.SESSION_USER_WEIXIN,userInfo.getWeiXin());
		}
		Token token=TokenGenerator.create(claims);
		return ResponseUtil.ok(token);
	}
	
	/**
	 * 处理用户登陆
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "login", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户登陆",notes = "处理用户登陆")
	public Response login(HttpServletRequest request,HttpServletResponse response,@RequestBody UserLoginForm userLoginForm) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		if (StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传!");
		}
		if (StringUtils.isEmpty(userLoginForm.getPassword())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"password必传!");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user == null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		try {
			user.setMacUid(userLoginForm.getMacUid());
			user.setRegisterIp(userLoginForm.getIp());
			user.setBrowser(userLoginForm.getBrowser());
			user.setJpushCode(userLoginForm.getJpushCode());

			if(!StringUtils.isEmpty(userLoginForm.getOpenId()) && userLoginForm.getIsBind() == UserWeChatEnum.BIND.getCode()){
//				String openId = AccessToken.getOpenid(userLoginForm.getCode());
//				if(StringUtils.isEmpty(openId)){
//					return ResponseUtil.error(ErrorCode.BIND_USER_OPENID,"获取用户openid失败!");
//				}
				if(StringUtils.isEmpty(user.getOpenId())){
					user.setOpenId(userLoginForm.getOpenId());
				}

			}
			if (user.getStatus() == UserStatusEnum.UN_DATA) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.UN_DATA,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.AUDIT) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.AUDIT,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.DISABLE) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.DISABLE,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.UN_AUDIT) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.UN_AUDIT,user.getId());
			}
			if (user.getStatus() == UserStatusEnum.UN_DATA_AUDIT) {//资料不正确
				return ResponseUtil.errorData(ErrorCode.UN_DATA_AUDIT,user.getId());
			}
			if (!PasswordHashUtil.validatePassword(userLoginForm.getPassword(), user.getPassword())) {
	            return ResponseUtil.errorData(ErrorCode.USER_PASSWORD_INVALID,"密码错误",user.getId());
	        }
			System.err.println("----------------1-----------------["+user.getLastUpdateTime()+"]");
			if(user.getLastUpdateTime()==null){
				System.err.println("----------------2-----------------"+user.getJpushCode());
				
				UserCompanyInfo findCompanyForm=new UserCompanyInfo();
				findCompanyForm.setUserId(user.getId());
				UserCompanyInfo companyForm=userCompanyInfoService.findOne(findCompanyForm);
				
				UserInfos userInfos=new UserInfos();
				userInfos.setCityId(companyForm.getCityId());
				userInfos.setDistrictId(companyForm.getDistrictId());
				userInfos.setProvinceId(companyForm.getProvinceId());
				Long count=userService.countUserList(userInfos);
				
				if(count>0l){
					String msString= "恭喜您成为安石派的会员，同行大厅有"+count+"个同行等待你去添加，安石派会助您迅速扩展人 脉、提升业绩！";
					
					List<String> clientList=new ArrayList<String>();
					clientList.add(user.getJpushCode());
					
					try {
						Map<String, Object> data=new HashMap<String, Object>();
						Map<String, Object> params=new HashMap<String, Object>();
						params.put("id", null);
						params.put("content",msString);
						data.put("type", "2");
						data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
						SpringUtils.getBean(JpushInterface.class).sendAllClientsPushMessage(clientList,"notification", data);
						
						java.util.Date  date=new java.util.Date();
						DataObject dataObject=new DataObject();
						dataObject.setJpushCode(clientList);
						dataObject.setMsg(msString);
						
						date=DateTimeUtil.addHours(date, 1);
						String cron=date.getSeconds()+ " "+DateTimeUtil.getMinutesOfHour(date)+" "+DateTimeUtil.getHoursOfDay(date)+" "+DateTimeUtil.getDayOfMonth(date)+" "+DateTimeUtil.getMonthOfYear(date)+" ? "+DateTimeUtil.getYearOfDate(date);
						SysScheduleJob scheduleJob2= new SysScheduleJob();
						scheduleJob2.setCronExpression(cron);
						scheduleJob2.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
						scheduleJob2.setJobName("TaskExcutor.pushMsg.02."+companyForm.getUserId());
						scheduleJob2.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
						scheduleJob2.setMethodName("pushMsg");
						sysScheduleJobService.addJob(scheduleJob2);
						
						date=DateTimeUtil.addHours(date, 1);
						cron=date.getSeconds()+ " "+DateTimeUtil.getMinutesOfHour(date)+" "+DateTimeUtil.getHoursOfDay(date)+" "+DateTimeUtil.getDayOfMonth(date)+" "+DateTimeUtil.getMonthOfYear(date)+" ? "+DateTimeUtil.getYearOfDate(date);
						SysScheduleJob scheduleJob3= new SysScheduleJob();
						scheduleJob3.setCronExpression(cron);
						scheduleJob3.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
						scheduleJob3.setJobName("TaskExcutor.pushMsg.03."+companyForm.getUserId());
						scheduleJob3.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
						scheduleJob3.setMethodName("pushMsg");
						sysScheduleJobService.addJob(scheduleJob3);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
			//user.setLastUpdateTime(new Timestamp(System.currentTimeMillis()));
			if(userService.update(user)<=0){
				return ResponseUtil.error("密码错误,请重新登录");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.errorData(ErrorCode.USER_PASSWORD_INVALID,"密码错误",user.getId());
		}
		try {
			UserInfo findUserInfo=new UserInfo();
			findUserInfo.setUserId(user.getId());
			UserInfo userInfo = userInfoService.findOne(findUserInfo);
			if (userInfo == null) {
				return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
			}
			Map<String, Object> claims = new HashMap<String, Object>();
			claims.put(MagicConstants.SESSION_USER_ID, user.getId());
			claims.put(MagicConstants.SESSION_USER_MOBILE,userLoginForm.getLoginId());
			claims.put(MagicConstants.SESSION_USER_JPUSH_CODE,userLoginForm.getJpushCode());
			claims.put(MagicConstants.SESSION_USER_WEIXIN,userInfo.getWeiXin());
			Token token=TokenGenerator.create(claims);
			//留做测试使用
			new CookieManager(request, response).setCookie(MagicConstants.User_Token,token.getToken(), 7*24*60*60*100);
			return ResponseUtil.ok(token);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.errorData(ErrorCode.USER_PASSWORD_INVALID,"密码错误",user.getId());
		}
	}
	/**
	 * 处理微信用户登陆
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "weChatLogin", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户微信端登陆",notes = "处理用户微信登陆")
	public Response weChatLogin(HttpServletRequest request,HttpServletResponse response,@RequestBody UserLoginForm userLoginForm) throws Exception {
		User user = new User();
		String openId = "";
		if(!StringUtils.isEmpty(userLoginForm.getCode())){
			openId = AccessToken.getOpenid(userLoginForm.getCode());
			if(StringUtils.isEmpty(openId)){
				return ResponseUtil.error(ErrorCode.BIND_USER_OPENID,"获取用户openid失败!");
			}
			userLoginForm.setOpenId(openId);
			user.setOpenId(openId);
			user = userService.findOne(user);
			if(user == null){
				return ResponseUtil.errorData(ErrorCode.BIND_USER_OPENID,"用户未绑定公众号!",openId);
			}
		}
		try {
			if (user.getStatus() == UserStatusEnum.UN_DATA) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,user.getId().toString(),openId);
			}
			if (user.getStatus() == UserStatusEnum.AUDIT) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,user.getId().toString(),openId);
			}
			if (user.getStatus() == UserStatusEnum.DISABLE) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,user.getId().toString(),openId);
			}
			if (user.getStatus() == UserStatusEnum.UN_AUDIT) {//0:待审核、1:正常、2:冻结
				return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,user.getId().toString(),openId);
			}
			if (user.getStatus() == UserStatusEnum.UN_DATA_AUDIT) {//资料不正确
				return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,user.getId().toString(),openId);
			}

		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,"自动登录失败!",openId);
		}
		try {
			UserInfo userInfo = new UserInfo();
			userInfo.setUserId(user.getId());
			userInfo = userInfoService.findOne(userInfo);
			if (userInfo == null) {
				return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,"自动登录失败!",openId);
			}
			Map<String, Object> claims = new HashMap<String, Object>(12);
			claims.put(MagicConstants.SESSION_USER_ID, user.getId());
			claims.put(MagicConstants.SESSION_USER_MOBILE,user.getLoginId());
			claims.put(MagicConstants.SESSION_USER_JPUSH_CODE,user.getJpushCode());
			claims.put(MagicConstants.SESSION_USER_WEIXIN,userInfo.getWeiXin());
			Token token = TokenGenerator.create(claims);
			token.setState(userLoginForm.getState());
			//留做测试使用
			new CookieManager(request, response).setCookie(MagicConstants.User_Token,token.getToken(), 7*24*60*60*100);
			return ResponseUtil.ok(token);
		} catch (Exception e) {
			e.printStackTrace();
			return ResponseUtil.errorData(ErrorCode.BIND_USER_LOGIN,"自动登录失败!",user.getId());
		}
	}

	/**
	 * 处理用户更新
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "updateUser", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "更新用户",notes = "处理用户更新")
	public Response updateUser(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,HttpServletRequest request,HttpServletResponse response,@RequestBody UserLoginForm userLoginForm) {
		if (StringUtils.isEmpty(userLoginForm.getJpushCode())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"jpushCode必传!");
		}
		User user = userService.get(userId);
		user.setMacUid(userLoginForm.getMacUid());
		user.setRegisterIp(userLoginForm.getIp());
		user.setBrowser(userLoginForm.getBrowser());
		user.setJpushCode(userLoginForm.getJpushCode());
		if(userService.update(user)<=0){
			return ResponseUtil.error(ErrorCode.UPDATE_DATA_ERROR);
		}
		return ResponseUtil.ok(user.getId());
	}

	
	@RequestMapping(value = "sendRegisterVerifCode", method = RequestMethod.POST)
	@ResponseBody
	@IgnoreAuth
	@CrossOrigin
	@ApiOperation(value = "发送注册验证码",notes = "发送注册验证码")
	public Response sendRegisterVerifCode(@RequestBody UserLoginForm userLoginForm) {
		if (userLoginForm==null||StringUtils.isEmpty(userLoginForm.getLoginId())) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"loginId必传!");
		}
		User findUser=new User();
		findUser.setLoginId(userLoginForm.getLoginId());
		User user = userService.findOne(findUser);
		if (user != null) {
			return ResponseUtil.error(ErrorCode.OBJECT_EXITS,"用户已经存在");
		}
		String code = RandomStringUtils.randomNumeric(4);
		appSmsService.sendToUID(AppSmsMessages.getMsg(AppSmsMessages.REGISTER_MSG, code), userLoginForm.getLoginId(),  code,AppSmsType.VERIF_CODE, DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(),5));
		return ResponseUtil.ok();
	}

	
	@RequestMapping(value = "sendVerifCode", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@IgnoreAuth
	@ApiOperation(value = "发送通用验证码",notes = "发送通用验证码")
	public Response sendVerifCode(@RequestBody UserLoginForm userLoginForm) {
		if(StringUtils.isEmpty(userLoginForm.getPhone())){
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"phone必传!");
		}
		if(!StringUtils.isEmpty(userLoginForm.getLoginId())){
			User findUser = new User();
			findUser.setLoginId(userLoginForm.getLoginId());
			User sysUser = userService.findOne(findUser);
			if (sysUser == null) {
				return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
			}
			userLoginForm.setPhone(userLoginForm.getLoginId());
		}
		String code = RandomStringUtils.randomNumeric(4);
		appSmsService.sendToUID(AppSmsMessages.getMsg(AppSmsMessages.REGISTER_MSG, code), userLoginForm.getPhone(), code,AppSmsType.VERIF_CODE, DateTimeUtil.addMinutes(DateTimeUtil.getSystemDate(),5));
		return ResponseUtil.ok();
	}

	
	/**
	 * 更新用户基本信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "更新用户基本信息",notes = "更新用户基本信息")
	public Response update(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody UserInfo userInfo){
		if (userInfo==null||userInfo.getId()==null) {
			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"id必传!");
		}
		userInfo.setUserId(userId);
		User updateUser=userService.get(userId);
		if (updateUser==null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		UserInfo findUserInfo=new UserInfo();
		findUserInfo.setUserId(userId);
		UserInfo updateUserInfo=userInfoService.findOne(findUserInfo);
		if (updateUserInfo==null) {
			return ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS,"用户不存在");
		}
		userInfo.setIntegral(updateUserInfo.getIntegral());
		userInfo.setCreateTime(updateUserInfo.getCreateTime());
		userInfo.setId(updateUserInfo.getId());
		boolean success=userService.updateUser(updateUser,userInfo);
		return ResponseUtil.ok(success);
	}

	/**
	 * 同行大厅
	 * @param user
	 * @return
	 */
	@IgnoreAuth
	@RequestMapping(value = "findList", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "分页获取全部同行用户",notes = "分页获取全部同行用户")
	public Response findByGroupCustomer(@RequestBody UserInfos user){
		Page<UserInfos> result=userService.findUserList(user);
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		Map<String, List<SysDictSmall>> companyValues = CommonDict.getFileds("user_company_info");

		Map<String, Object> maps=new HashMap<String, Object>();

		maps.put("userInfos", result);
		maps.put("defaultInfo", values);
		maps.put("defaultCompany", companyValues);

		return ResponseUtil.ok(maps);
	}
	/**
	 * 用户所在地区同行且未添加为好友
	 * @param user
	 * @return
	 */
	@IgnoreAuth
	@RequestMapping(value = "findMyAreaUserList", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取用户所在地区同行",notes = "获取用户所在地区同行")
	public Response findMyAreaUserList(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody UserInfos user){
		if(userId == null){
			ResponseUtil.error("用户未登录");
		}
		user.setId(userId);
		Page<UserInfos> result=userService.findMyAreaUserList(user);
		Map<String, List<SysDictSmall>> values = CommonDict.getFileds("user_info");
		Map<String, List<SysDictSmall>> companyValues = CommonDict.getFileds("user_company_info");

		Map<String, Object> maps=new HashMap<String, Object>();

		maps.put("userInfos", result);
		maps.put("defaultInfo", values);
		maps.put("defaultCompany", companyValues);

		return ResponseUtil.ok(maps);
	}
	/**
	 * 用户所在地区同行且未添加为好友数量
	 * @param user
	 * @return
	 */
	@IgnoreAuth
	@RequestMapping(value = "findMyAreaUserCount", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取用户所在地区同行数量",notes = "获取用户所在地区同行数量")
	public Response findMyAreaUserCount(@ApiParam(name="id",value="用户id",hidden=true) @CurrentUserId Long userId,@RequestBody UserInfos user){
		if(userId == null){
			ResponseUtil.error("用户未登录");
		}
		user.setId(userId);
		long count = userService.findMyAreaUserCount(user);
		return ResponseUtil.ok(count);
	}

	/**
	 * 增加甩单信息
	 */
	@IgnoreAuth
	@RequestMapping(value = "getByUserId2", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取Id用户信息",notes = "获取默认用户信息")
	public Response getByUserId2(@ApiParam(name="userId",value="用户id",required = true) @RequestBody User user){
        if(null == user.getId()){
			return ResponseUtil.error("用户ID必传!");
		}
		UserAndCompanyInfo userAndCompanyInfo= userInfoService.getUserAndCompanyInfo(user.getId()) ;
		System.out.println("user.getRejectionId()user.getRejectionId()user.getRejectionId():"+user.getRejectionId());
		if(user.getRejectionId()!=null){
			Rejection rejection = rejectionService.get(user.getRejectionId());
			userAndCompanyInfo.setRejection(rejection);
		}else{
			Rejection findRejection=new Rejection();
			findRejection.setUserId(user.getId());
			findRejection.setOrderBy("CRM_REJECTION.create_time desc ");
			Rejection rejection=rejectionService.findOne(findRejection);
			userAndCompanyInfo.setRejection(rejection);
		}
		return ResponseUtil.ok(userAndCompanyInfo);
	}

	@IgnoreAuth
	@RequestMapping(value = "getByUserId", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取Id用户信息",notes = "获取默认用户信息")
	public Response getByUserId(@ApiParam(name="userId",value="用户id",required = true) @RequestBody User user){
        if(null == user.getId()){
			return ResponseUtil.error("用户ID必传!");
		}
		UserAndCompanyInfo userAndCompanyInfo= userInfoService.getUserAndCompanyInfo(user.getId()) ;
		return ResponseUtil.ok(userAndCompanyInfo);
	}
	@IgnoreAuth
	@RequestMapping(value = "jPushAlert", method = RequestMethod.POST)
	@ResponseBody
	@CrossOrigin
	@ApiOperation(value = "获取Id用户信息",notes = "获取默认用户信息")
	public Response jPushAlert(@ApiParam(name="userId",value="用户id",required = true) @RequestBody User user){
		userService.sendPushForAlert(user.getJpushCode(),user.getUserName()) ;
		return ResponseUtil.ok();

	}
	
//	/**
//	 * 更新用户基本信息
//	 */
//	@RequestMapping(value = "getUserAndCompanyInfo", method = RequestMethod.POST)
//	@ResponseBody
//	@ApiOperation(value = "获取用户基本信息",notes = "获取用户基本信息")
//	public Response getUserAndCompanyInfo(@RequestBody Long userId){
//		if (userId==null||userId==null) {
//			return ResponseUtil.error(ErrorCode.PARAMETER_INVALID,"id必传!");
//		}
//		UserCompanyInfo findUserCompanyInfo=new UserCompanyInfo();
//		findUserCompanyInfo.setUserId(userId);
//		UserCompanyInfo userCompanyInfo=userService.findOne(findUserCompanyInfo);
//		if(userCompanyInfo!=null){
//			userCompanyInfo.setCompanyName(companyForm.getCompanyName());
//			userCompanyInfo.setDistrictId(companyForm.getDistrictId());
//			userCompanyInfo.setProvinceId(companyForm.getProvinceId());
//			userCompanyInfo.setCityId(companyForm.getCityId());
//			userCompanyInfo.setProvinceName(companyForm.getProvinceName());
//			userCompanyInfo.setDistrictName(companyForm.getDistrictName());
//			userCompanyInfo.setCityName(companyForm.getCityName());
//			if(userCompanyInfoDao.update(userCompanyInfo)>0){
//				return userCompanyInfo;
//			}
//		}else{
//			throw new ServiceException(ErrorCode.NOT_FIND_USER_COMPANY);
//		}
//		return ResponseUtil.ok(success);
//	}
	
	
	
	/**
	 * 通过手机验证码直接登陆
	 * @param request
	 * @param response
	 * @param userLoginForm
	 * @return
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "/loginByMobileCode")
	@ResponseBody
	@ApiOperation(value = "验证码登陆",notes = "手机验证码登陆")
	public Response loginByMobileCode(@CurrentUserId Long userId,@RequestBody UserLoginForm userLoginForm,HttpServletRequest request,HttpServletResponse response) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalArgumentException, JWTCreationException, UnsupportedEncodingException {
		Response result = new Response();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		logger.debug("UserController loginByMobileCode userLoginForm:"+userLoginForm);
		
		if (StringUtil.isEmpty(userLoginForm.getPhone())) {
			//手机号不能为空
			result = ResponseUtil.error(ErrorCode.SHARE_MOBILE_NUL);
		}
		else if (StringUtils.isEmpty(userLoginForm.getVerifCode())) {
			//验证码不能为空
			result = ResponseUtil.error(ErrorCode.SHARE_CODE_NULL);		
		}
		else {
			
			//String patternStr1 = "^((13[0-9])|(15[0-9])|(18[0-9]))\\d{8}$";  
			String patternStr = "^(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}$";  
			Pattern pattern = Pattern.compile(patternStr);
			Matcher matcher = pattern.matcher(userLoginForm.getPhone());
			if (!matcher.matches()) {
				//手机格式不正确
				result = ResponseUtil.error(ErrorCode.MOBILE_WRONGFUL);
			}
			else {
				ShareQuery shareQuery = new ShareQuery();
				//此手机号有无验证码,参数：手机号
				logger.debug("UserController loginByMobileCode userLoginForm.getPhone():"+userLoginForm.getPhone());
				shareQuery.setMobile(Long.parseLong(userLoginForm.getPhone()));
				logger.debug("UserController loginByMobileCode shareQuery1:"+shareQuery);
		        Boolean hasMobile = shareService.hasMobile(shareQuery);
		        if (hasMobile) {
		            return ResponseUtil.error(ErrorCode.SHARE_MOBILE_NO_CODE);
		        }
		        
		        if ("13917401747".equals(userLoginForm.getPhone())  || "17601392466".equals(userLoginForm.getPhone()) ) {
					if (!"123456".equals(userLoginForm.getVerifCode())) {
						return ResponseUtil.error(ErrorCode.SHARE_CODE_ERROR);
					}
				}
		        else { 
			        //验证验证码时间,参数：手机号
			        Boolean timeFlg = shareService.verifyCodeTime(shareQuery);   //false是没过期,true过期
			        if (timeFlg) {
			            return ResponseUtil.error(ErrorCode.SHARE_CODE_OUT);
			        }
			        
			        //验证验证码,参数：手机号、验证码
					logger.debug("UserController loginByMobileCode userLoginForm.getCode():"+userLoginForm.getVerifCode());
					shareQuery.setCode(Long.parseLong(userLoginForm.getVerifCode()));
					logger.debug("UserController loginByMobileCode shareQuery2:"+shareQuery);
			        Boolean verify = shareService.verifyCode(shareQuery);
			        if (!verify) {
			            return ResponseUtil.error(ErrorCode.SHARE_CODE_ERROR);
			        }
		        }
		        
		        //根据用户loginId（手机号）查询用户信息
				User findUser = new User();
			    findUser.setLoginId(userLoginForm.getLoginId());
			    logger.debug("UserController loginByMobileCode userService.findOne request:"+findUser);
			    User user = userService.findOne(findUser);
				logger.debug("UserController loginByMobileCode userService.findOne response:"+user);
			    //存在
		    	User user1 = null;
			    if (user != null) {
					user.setMacUid(userLoginForm.getMacUid());		//机器编号
					user.setRegisterIp(userLoginForm.getIp());		//注册IP
					user.setBrowser(userLoginForm.getBrowser());	//浏览器
					user.setJpushCode(userLoginForm.getJpushCode());//jpush通讯Code
					logger.debug("UserController loginByMobileCode user2:"+user);
					
					//设置微信用户openId
					if(!StringUtils.isEmpty(userLoginForm.getOpenId()) && userLoginForm.getIsBind() == UserWeChatEnum.BIND.getCode()){
				        if(StringUtils.isEmpty(user.getOpenId())){
				        	user.setOpenId(userLoginForm.getOpenId());	//微信用户openId
				        	logger.debug("UserController loginByMobileCode userLoginForm.getOpenId()..."+userLoginForm.getOpenId());
				        }
					}
					
					//0:待审核,1:正常,2:冻结,3:审核未通过,4:待完善企业信息
					resultMap.put("id", user.getId());
					resultMap.put("userType", user.getUserType());
					resultMap.put("userStatus", user.getStatus());
					resultMap.put("isNewUser", "false");
					
					logger.debug("UserController loginByMobileCode user.getStatus()..."+user.getStatus());
					
					if (user.getStatus() == UserStatusEnum.UN_DATA) {	//4, "待完善企业信息"
						result = ResponseUtil.errorData(ErrorCode.UN_DATA, resultMap);
					}
					else if (user.getStatus() == UserStatusEnum.AUDIT) { //0, "待审核"
						result = ResponseUtil.errorData(ErrorCode.AUDIT, resultMap);
					}
					else if (user.getStatus() == UserStatusEnum.DISABLE) { // 2, "冻结"
						result = ResponseUtil.errorData(ErrorCode.DISABLE, resultMap);
					}
					else if (user.getStatus() == UserStatusEnum.UN_AUDIT) { // 3, "审核未通过"
						result = ResponseUtil.errorData(ErrorCode.UN_AUDIT, resultMap);
					}
					else if (user.getStatus() == UserStatusEnum.UN_DATA_AUDIT) { //5, "资料不正确"
						result = ResponseUtil.errorData(ErrorCode.UN_DATA_AUDIT, resultMap);
					}
					else {
						logger.debug("UserController loginByMobileCode user.getLastUpdateTime():" + user.getLastUpdateTime());
						//最后更新时间为空，即为第一次登录，推送同行信息
						if(null == user.getLastUpdateTime() ){
							//查询企业信息
							UserCompanyInfo findCompanyForm=new UserCompanyInfo();
					        findCompanyForm.setUserId(user.getId());
					        UserCompanyInfo companyForm=userCompanyInfoService.findOne(findCompanyForm);
					        //根据企业信息中的地址编号查询所在城市的同行的总人数
					        UserInfos userInfos=new UserInfos();
					        userInfos.setCityId(companyForm.getCityId());
					        userInfos.setDistrictId(companyForm.getDistrictId());
					        userInfos.setProvinceId(companyForm.getProvinceId());
					        Long count = userService.countUserList(userInfos);
							//总人数大于0就推送一条信息
					        if (count>0) {
					        	String msString= "恭喜您成为安石派的会员，同行大厅有"+count+"个同行等待你去添加，安石派会助您迅速扩展人 脉、提升业绩！";
						          
								List<String> clientList = new ArrayList<String>();
								clientList.add(user.getJpushCode());

								//定时任务，推送
								try {
									Map<String, Object> data = new HashMap<String, Object>();
									Map<String, Object> params = new HashMap<String, Object>();
									params.put("id", null);
									params.put("content", msString);
									data.put("type", "2");
									data.put("data", JsonMapper.nonDefaultMapper().toJson(params));
									SpringUtils.getBean(JpushInterface.class).sendAllClientsPushMessage(clientList, "notification", data);

									java.util.Date date = new java.util.Date();
									DataObject dataObject = new DataObject();
									dataObject.setJpushCode(clientList);
									dataObject.setMsg(msString);

									date = DateTimeUtil.addHours(date, 1);
									String cron = date.getSeconds() + " " + DateTimeUtil.getMinutesOfHour(date) + " "
											+ DateTimeUtil.getHoursOfDay(date) + " " + DateTimeUtil.getDayOfMonth(date) + " "
											+ DateTimeUtil.getMonthOfYear(date) + " ? " + DateTimeUtil.getYearOfDate(date);
									SysScheduleJob scheduleJob2 = new SysScheduleJob();
									scheduleJob2.setCronExpression(cron);
									scheduleJob2.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
									scheduleJob2.setJobName("TaskExcutor.pushMsg.02." + companyForm.getUserId());
									scheduleJob2.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
									scheduleJob2.setMethodName("pushMsg");
									sysScheduleJobService.addJob(scheduleJob2);

									date = DateTimeUtil.addHours(date, 1);
									cron = date.getSeconds() + " " + DateTimeUtil.getMinutesOfHour(date) + " "
											+ DateTimeUtil.getHoursOfDay(date) + " " + DateTimeUtil.getDayOfMonth(date) + " "
											+ DateTimeUtil.getMonthOfYear(date) + " ? " + DateTimeUtil.getYearOfDate(date);
									SysScheduleJob scheduleJob3 = new SysScheduleJob();
									scheduleJob3.setCronExpression(cron);
									scheduleJob3.setJobGroup("com.tiger.cloud.service.system.TaskExcutor");
									scheduleJob3.setJobName("TaskExcutor.pushMsg.03." + companyForm.getUserId());
									scheduleJob3.setTempId(JsonMapper.nonDefaultMapper().toJson(dataObject));
									scheduleJob3.setMethodName("pushMsg");
									sysScheduleJobService.addJob(scheduleJob3);
								} catch (Exception e) {
									e.printStackTrace();
								}
							}
						}
					}
			    } else {
			    	System.out.println("userId"+userId);
			    	//为空-->第一次登录操作
			    	//该手机号从未登陆过，新用户
			    	//设置token
			    	logger.debug("UserController loginByMobileCode userService.findOne is null.");
			    	try {
			    		userLoginForm.setPassword("000000");
			    		user1 = userService.register(userLoginForm);
			    		
			    		//修改用户为企业用户
			    		User updateUser = new User();
			    		updateUser.setUserType(1);
			    		updateUser.setId(user1.getId());
			    		userService.update(updateUser);
			    		
			    		//0:待审核,1:正常,2:冻结,3:审核未通过,4:待完善企业信息
						resultMap.put("id", user1.getId());
						resultMap.put("userType", user1.getUserType());
						resultMap.put("userStatus", user1.getStatus());
					} catch (Exception e) {
						e.printStackTrace();
					}
			    	logger.debug("UserController loginByMobileCode response[user1]:"+user1);
					if ( null != user1) {
						//完善crm_user_info
						UserInfo userinfo = new UserInfo();
						userinfo.setUserId(user1.getId());
						userinfo.setLoginId(user1.getLoginId());
						userinfo.setMobile(user1.getLoginId());
						userinfo.setIsDelete(DeleteEnum.NOMAIL);
						userInfoService.insert(userinfo);
						
						//0:待审核,1:正常,2:冻结,3:审核未通过,4:待完善企业信息
						resultMap.put("id", user1.getId());
						resultMap.put("userStatus", user1.getStatus());
						resultMap.put("isNewUser", "true");
					}
					else {
						result = ResponseUtil.error(ErrorCode.INSERT_DATA_ERROR);
					}
			    }
			    
			    //设置token
				try {
					Long ids = null;
					if (null != user ) {
						ids = user.getId();
					}
					else if(null != user1){
						ids = user1.getId();
					}
			    	logger.debug("UserController loginByMobileCode ids:::"+ids);
					Map<String, Object> claims = new HashMap<String, Object>();
					logger.debug("UserController loginByMobileCode token request[]:" + ids+","+userLoginForm.getPhone()+","+
							userLoginForm.getJpushCode()+","+userLoginForm.getOpenId());
					claims.put(MagicConstants.SESSION_USER_ID, ids);
					claims.put(MagicConstants.SESSION_USER_MOBILE, userLoginForm.getPhone());
					claims.put(MagicConstants.SESSION_USER_JPUSH_CODE, userLoginForm.getJpushCode());
					claims.put(MagicConstants.SESSION_USER_WEIXIN, userLoginForm.getOpenId());
					Token token = TokenGenerator.create(claims);
					// 留做测试使用
					new CookieManager(request, response).setCookie(MagicConstants.User_Token, token.getToken(), 7 * 24 * 60 * 60 * 100);
					
					resultMap.put("token", token.getToken());
					resultMap.put("expireSeconds", token.getExpireSeconds());
					resultMap.put("state", token.getState());
					result = ResponseUtil.ok(resultMap);
					
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}//手机号格式正确
		}//所有数据不为空
		result.setData(resultMap);
		logger.debug("UserController loginByMobileCode response[result]:" + result);
		return result;
	}
	
	
	
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "/getToken")
	@ResponseBody
	@ApiOperation(value = "获取一个Token值",notes = "获取一个Token值")
	public Response getToken(String id,String loginId,String jpushCode,HttpServletRequest request,HttpServletResponse response) {
		logger.debug("UserController getToken request:" + id+","+loginId+","+jpushCode);
		Response result = new Response();
		try {
			if (StringUtil.isEmpty(id)) {
				ResponseUtil.error(ErrorCode.USER_ID_NULL);
			}
			else if (StringUtil.isEmpty(loginId)) {
				ResponseUtil.error(ErrorCode.SHARE_MOBILE_NUL);
			}
			else if (StringUtil.isEmpty(jpushCode)) {
				ResponseUtil.error(ErrorCode.JPUSH_NULL);
			}
			else {
				UserInfo findUserInfo = new UserInfo();
				findUserInfo.setUserId(Long.parseLong(id));
				UserInfo userInfo = userInfoService.findOne(findUserInfo);
				if (userInfo != null) {
					Map<String, Object> claims = new HashMap<String, Object>();
					claims.put(MagicConstants.SESSION_USER_ID, id);
					claims.put(MagicConstants.SESSION_USER_MOBILE, loginId);
					claims.put(MagicConstants.SESSION_USER_JPUSH_CODE, jpushCode);
					claims.put(MagicConstants.SESSION_USER_WEIXIN, userInfo.getWeiXin());
					Token token = TokenGenerator.create(claims);
					// 留做测试使用
					new CookieManager(request, response).setCookie(MagicConstants.User_Token, token.getToken(), 7 * 24 * 60 * 60 * 100);
				}
				else {
					result = ResponseUtil.error(ErrorCode.OBJECT_NOT_EXITS);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		logger.debug("UserController getToken response[result]:" + result);
		return result;
	}
	
	
	
	/**
	 * 登陆时直接发送验证码
	 * @param phone
	 * @return
	 */
	@IgnoreAuth
	@CrossOrigin
	@RequestMapping(value = "/sendCode")
	@ApiOperation(value = "用户通过短信登陆",notes = "用户通过短信登陆")
	@ResponseBody
	public Response sendCode(String phone) {
		logger.debug("UserController sendCode phone:"+phone);
		Response result = new Response();
		if (StringUtil.isEmpty(phone)) {
			result = ResponseUtil.error(ErrorCode.SHARE_MOBILE_NUL);
		}
		else {
	        String patternStr = "^(13\\d|14[579]|15[^4\\D]|17[^49\\D]|18\\d)\\d{8}$";  
			Pattern pattern = Pattern.compile(patternStr);
			Matcher matcher = pattern.matcher(phone);
			if (matcher.matches()) {
				ShareQuery shareQuery = new ShareQuery();
				shareQuery.setMobile(Long.parseLong(phone));
				Boolean isSuccess = shareService.getVCode(shareQuery);
				if (!isSuccess) {
					result = ResponseUtil.error();
				}
			}
			else {
				result = ResponseUtil.error(ErrorCode.MOBILE_WRONGFUL);
			}
		}
		result.setData(null);
		logger.debug("UserController sendCode response[result]:" + result);
		return result;
	}
	
	
	
	
	
	
	
	
}